/*
 * @Author: 郭招娣 10615594+guo-zhaodi@user.noreply.gitee.com
 * @Date: 2022-09-12 11:32:15
 * @LastEditors: 郭招娣 10615594+guo-zhaodi@user.noreply.gitee.com
 * @LastEditTime: 2022-09-14 11:56:46
 * @FilePath: \郭招娣\app\src\store\modules\login.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

import { asyncLogins } from '../../api/index'
import routerList from '../../router/addRouter'
import { filterRouter } from '../../utils/common'

import { ElMessage } from "element-plus";

import router from '../../router'

export default {
    namespaced: 'login',
    state: {
        // 用户信息
        user: {},
        // 用户的权限
        author: localStorage.getItem('author') || '',
        token: localStorage.getItem('token') || '',
        // 动态的路由表
        routerList: [],
    },
    mutations: {
        getUser(state, payload) {
            state.user = { ...payload };
            state.author = payload.author;
            state.token = payload.token;
            // state.username=
            localStorage.setItem('author', payload.author);
            localStorage.setItem('user', JSON.stringify(payload));

        },
        // 存储动态的路由表
        getRouter(state, payload) {
            state.routerList = payload;
        }
    },
    actions: {
        // 登陆方法
        async actionLogin({ commit, dispatch }, payload) {
            const res = await asyncLogins('/login', payload);
            if (res.data.code === 200) {
                ElMessage({
                    message: res.data.msg,
                    type: "success",
                });
                
            } else {
                ElMessage({
                    message: res.data.msg,

                });
            }
            localStorage.setItem('token', res.data.token);

            dispatch('setRouterList', res.data.author);
           
            // 存储用户的信息
            commit('getUser', res.data);
        },

        // 设置动态路由
        setRouterList({ commit }, payload) {
            // payload => 路由权限 TC USER
            // 获取最新的路由表
            const routes = filterRouter(routerList, payload);

            // 动态添加路由
            routes.forEach(item => {
                router.addRoute(item);
            })
            // 跳页面
            router.push(routes[0].path);

            // 存储 路由表
            commit('getRouter', routes);
        }
    },
    modules: {
    }
}

